package com.zzzy.doc.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzzy.common.util.AssertUtil;
import com.zzzy.doc.dao.entity.DocFile;
import com.zzzy.doc.dao.entity.DocFileTemplate;
import com.zzzy.doc.dao.mapper.DocFileMapper;
import com.zzzy.framework.common.enums.common.TemplateStatusEnum;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 公文文件信息
 *
 * @author fc
 * @since 2024-08-12
 */
@Service
public class DocFileService extends ServiceImpl<DocFileMapper, DocFile> {

    @Resource
    private DocFileTemplateService docFileTemplateService;

    public void addDocFileByTemplateId(Long docId, Long templateId) {
        DocFile docFile = new DocFile();
        docFile.setDocId(docId);
        DocFileTemplate template = docFileTemplateService.getByIdForQuery(templateId);
        AssertUtil.isEquals(TemplateStatusEnum.ENABLE.getValue(), template.getStatus(), "公文文件模板状态错误");
        docFile.setTemplateName(template.getName());
        docFile.setApprovalFileBlob(template.getApprovalFileBlob());
        docFile.setApprovalDataRegions(template.getApprovalDataRegions());
        docFile.setMainFileBlob(template.getMainFileBlob());
        docFile.setMainInitDataTags(template.getMainInitDataTags());
        docFile.setMainRevisionCount(0);
        baseMapper.insert(docFile);
    }

    public void updateApprovalByDocId(Long docId, byte[] fileBytes) {
        DocFile docFile = getDocFileByDocId(docId);
        docFile.setApprovalFileBlob(fileBytes);
        baseMapper.updateById(docFile);
    }

    public void updateMainByDocId(Long docId, byte[] fileBytes, Integer revisionCount) {
        DocFile docFile = getDocFileByDocId(docId);
        docFile.setMainFileBlob(fileBytes);
        docFile.setMainRevisionCount(revisionCount);
        baseMapper.updateById(docFile);
    }

    public void updateFinalPdfByDocId(Long docId, byte[] fileBytes) {
        DocFile docFile = getDocFileByDocId(docId);
        docFile.setPdfFileBlob(fileBytes);
        baseMapper.updateById(docFile);
    }

    public DocFile getDocFileByDocId(Long docId) {
        DocFile docFile = baseMapper.selectOne(new LambdaQueryWrapper<DocFile>().eq(DocFile::getDocId, docId));
        AssertUtil.nonNull(docFile, "公文文件不存在");
        return docFile;
    }

    public void updateRedSheetFile(Long docId, byte[] fileBytes) {
        DocFile docFile = getDocFileByDocId(docId);
        docFile.setRedSheetFileBlob(fileBytes);
        baseMapper.updateById(docFile);
    }

}
